import React, { useRef, useState } from 'react';
import Card from './Card';

interface ConnectionStatusProps {
  status?: string;
  downloadSpeed?: number;
  uploadSpeed?: number;
  isConnecting?: boolean;
}

const ConnectionStatus: React.FC<ConnectionStatusProps> = ({
  status = "连接中",
  downloadSpeed = 0,
  uploadSpeed = 0,
  isConnecting = true
}) => {
  // 圆形进度条组件 - scaled down version
  const CircularProgress: React.FC<{
    percentage: number;
    value: string;
    label: string;
    unit: string;
  }> = ({ percentage, value, label, unit }) => {
    const radius = 10; // Reduced from 40
    const circumference = 2 * Math.PI * radius;
    const strokeDasharray = circumference;
    const strokeDashoffset = circumference - (percentage / 100) * circumference;

    return (
      <div className="flex"> {/* Reduced spacing */}
        <div className="relative">
          <svg width="20" height="20" className="transform -rotate-90"> {/* Reduced from 90 */}
            {/* 背景圆 */}
            <circle
              cx="10"
              cy="10"
              r={radius}
              stroke="#e5e7eb"
              strokeWidth="5" // Reduced from 6
              fill="none"
            />
            {/* 进度圆 */}
            <circle
              cx="10"
              cy="10"
              r={radius}
              stroke="#3b82f6"
              strokeWidth="5" // Reduced from 6
              fill="none"
              strokeDasharray={strokeDasharray}
              strokeDashoffset={strokeDashoffset}
              strokeLinecap="round"
              className="transition-all duration-300 ease-in-out"
            />
          </svg>
          {/* 中心文字 */}
          <div className="absolute inset-0 flex items-center justify-center">
            <span className="text-[0.4rem] font-semibold text-blue-600"> {/* Reduced text size */}
              {percentage}%
            </span>
          </div>
        </div>
        {/* 右侧标签 */}
        <div className="flex flex-col">
          <div className="text-[0.4rem] font-medium text-gray-800"> {/* Reduced text size */}
            {value}{unit}
          </div>
          <div className="text-[0.4rem] text-gray-500"> {/* Reduced text size */}
            {label}
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="p-4 w-full h-full flex flex-col"> {/* Reduced padding */}
      {/* 标题 */}
      <div className="text-center mb-4"> {/* Reduced margin */}
        <h2 className="text-[0.6rem] font-bold text-blue-600 mb-1"> {/* Reduced text size and margin */}
          {status}
        </h2>

        {/* 状态指示器 */}
        <div className="flex items-center justify-center mb-1"> {/* Reduced margin */}
          <div className="w-1.5 h-1.5 bg-blue-500 rounded-full animate-pulse mr-1"></div> {/* Reduced size */}
          <span className="text-[0.5rem] text-gray-600">0mm</span> {/* Reduced text size */}
        </div>

        {/* 状态描述 */}
        <div className="text-[0.25rem] text-gray-500"> {/* Further reduced text size */}
          正在建立连接
        </div>

        {/* 连接状态指示条 */}
        <div className="w-full bg-gray-200 rounded-full h-1 mt-2"> {/* Reduced margin */}
          <div className="bg-blue-500 h-1 rounded-full animate-pulse" style={{ width: '30%' }}></div>
        </div>
      </div>

      {/* 进度指示器 */}
      <div className="flex justify-around items-center flex-1">
        <CircularProgress
          percentage={0}
          value="0"
          label="网络速度"
          unit="mm/min"
        />
        <CircularProgress
          percentage={0}
          value="0"
          label="传输力"
          unit=" s/s"
        />
      </div>
    </div>
  );
};

const JerseyComponent = ({ text = "35.3bar", number = 5, rotation = 0 }) => {
  return (
    <div
      className="relative rounded-lg w-16 h-20"
      style={{ transform: `rotate(${rotation}deg)` }}
    >
      {/* 球衣主体 */}
      <div className="p-1 text-center h-full flex flex-col justify-center">
        {/* 号码 */}
        <div className="text-[5px] font-bold text-gray-800">{number}</div>

        {/* 两个圆形装饰 */}
        <div className="flex justify-center">
          <div className="w-2 h-2 bg-black rounded-full"></div>
          <div className="w-2 h-2 bg-black rounded-full"></div>
        </div>

      </div>
    </div>
  );
};


const CircularJerseyLayout = ({ containerRef }: { containerRef: React.RefObject<HTMLDivElement> }) => {
  const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });

  const jerseyData = [
    { number: 1, text: "32.1bar" },
    { number: 2, text: "28.5bar" },
    { number: 3, text: "41.2bar" },
    { number: 4, text: "35.8bar" },
    { number: 5, text: "29.3bar" },
    { number: 6, text: "38.7bar" },
    { number: 7, text: "33.4bar" },
    { number: 8, text: "42.1bar" },
    { number: 9, text: "31.6bar" },
    { number: 10, text: "36.9bar" },
    { number: 11, text: "27.8bar" },
    { number: 12, text: "39.5bar" },
    { number: 13, text: "34.2bar" },
    { number: 14, text: "40.3bar" },
    { number: 15, text: "30.7bar" },
    { number: 16, text: "37.4bar" },
    { number: 17, text: "35.3bar" }
  ];

  // 监听容器大小变化
  React.useEffect(() => {
    const updateSize = () => {
      if (containerRef?.current) {
        const { width, height } = containerRef.current.getBoundingClientRect();
        setContainerSize({ width, height });
      }
    };

    updateSize();
    window.addEventListener('resize', updateSize);

    let resizeObserver: ResizeObserver | null = null;
    if (containerRef?.current) {
      resizeObserver = new ResizeObserver(updateSize);
      resizeObserver.observe(containerRef.current);
    }

    return () => {
      window.removeEventListener('resize', updateSize);
      if (resizeObserver) {
        resizeObserver.disconnect();
      }
    };
  }, [containerRef]);

  // 计算相对尺寸
  const minDimension = Math.min(containerSize.width, containerSize.height);
  const radius = minDimension * 0.45; // 使用相对半径
  const centerX = containerSize.width / 2;
  const centerY = containerSize.height / 2;

  // 使用球衣中心点形成的圆心
  const visualCenterX = centerX;
  const visualCenterY = centerY;

  // Define jersey groups with colors
  const jerseyGroups = [
    { name: "red", numbers: [1, 2, 3], color: "#FF6B6B" },
    { name: "blue", numbers: [4, 5, 6, 7], color: "#4ECDC4" },
    { name: "yellow", numbers: [8, 9, 10, 11, 12], color: "#FECA57" },
    { name: "pink", numbers: [13, 14, 15, 16, 17], color: "#FF9FF3" }
  ];

  // Calculate group angles
  const groupAngles = jerseyGroups.map(group => {
    const startIndex = jerseyData.findIndex(j => j.number === group.numbers[0]);
    const endIndex = jerseyData.findIndex(j => j.number === group.numbers[group.numbers.length - 1]);
    return {
      color: group.color,
      startAngle: (startIndex * 360) / 17,
      endAngle: ((endIndex + 1) * 360) / 17
    };
  });

  return (
    <div className="relative w-full h-full flex items-center justify-center">
      {/* Group arcs */}
      {groupAngles.map((group, index) => {
        const startRadian = (group.startAngle * Math.PI) / 180 - Math.PI / 2;
        const endRadian = (group.endAngle * Math.PI) / 180 - Math.PI / 2;
        
        return (
          <svg
            key={index}
            className="absolute"
            style={{
              width: `${radius * 1.8}px`,
              height: `${radius * 1.8}px`,
              left: `${visualCenterX - radius * 0.9}px`,
              top: `${visualCenterY - radius * 0.9}px`,
            }}
            viewBox={`0 0 ${radius * 1.8} ${radius * 1.8}`}
          >
            <path
              d={`M ${radius * 0.9 + radius * 0.9 * Math.cos(startRadian)} ${
                radius * 0.9 + radius * 0.9 * Math.sin(startRadian)
              } A ${radius * 0.9} ${radius * 0.9} 0 ${
                group.endAngle - group.startAngle > 180 ? 1 : 0
              } 1 ${radius * 0.9 + radius * 0.9 * Math.cos(endRadian)} ${
                radius * 0.9 + radius * 0.9 * Math.sin(endRadian)
              }`}
              fill="none"
              stroke={group.color}
              strokeWidth="1"
            />
          </svg>
        );
      })}

      {/* Inner circle */}
      <div
        className="absolute bg-amber-50 rounded-full"
        style={{
          width: `${radius * 1.7}px`,
          height: `${radius * 1.7}px`,
          left: '50%',
          top: '50%',
          transform: 'translate(-50%, -50%)',
        }}
      >
        <ConnectionStatus status="连接中" downloadSpeed={20} uploadSpeed={40} isConnecting={true} />
      </div>

      {/* 17个球衣组件围成圆圈 */}
      {jerseyData.map((jersey, index) => {
        const angle = (index * 360) / 17;
        const radian = (angle * Math.PI) / 180;

        // 使用计算出的球衣中心点
        const x = centerX + radius * Math.cos(radian - Math.PI / 2);
        const y = centerY + radius * Math.sin(radian - Math.PI / 2);

        const rotationAngle = angle + 180;
        return (
          <div
            key={index}
            className="absolute transform -translate-x-1/2 -translate-y-1/2"
            style={{
              left: `${x}px`,
              top: `${y}px`,
            }}
          >
            <JerseyComponent
              number={jersey.number}
              text={jersey.text}
              rotation={rotationAngle}
            />
          </div>
        );
      })}
    </div>
  );
};


interface CircularLayoutProps {
  className?: string;
  style?: React.CSSProperties;
}

const CircularLayout: React.FC<CircularLayoutProps> = ({ className = '', style }) => {
  const containerRef = useRef<HTMLDivElement>(null!);
  return (
    <div
      className={`relative w-full h-full overflow-hidden ${className}`}
      style={style}
    >
      {/* 容器 */}
      <div className="relative w-full h-full" style={{ minHeight: '200px', minWidth: '200px' }}>

        {/* 中心大圆形组件 */}
        <div
          className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2
                     rounded-full flex items-center justify-center"
          style={{
            fontSize: 'clamp(0.875rem, 2.5vw, 1.25rem)',
            width: 'min(60%, 320px)',
            height: 'min(60%, 320px)',
          }}
          ref={containerRef}
        >
          <CircularJerseyLayout containerRef={containerRef} />
        </div>

        {/* 上方组件 */}
        <div
          className="absolute left-1/2 transform -translate-x-1/2
                     rounded-lg flex items-center justify-center
                     "
          style={{
            top: 'max(5%, 8px)',
            width: 'min(10%, 48px)',
            height: 'min(10%, 48px)',
            fontSize: 'clamp(0.75rem, 2vw, 1rem)'
          }}
        >
          <Card percentage={37.5} label="45bar" />
        </div>

        {/* 下方组件 */}
        <div
          className="absolute left-1/2 transform -translate-x-1/2
                     rounded-lg flex items-center justify-center"
          style={{
            bottom: 'max(5%, 8px)',
            width: 'min(10%, 48px)',
            height: 'min(10%, 48px)',
            fontSize: 'clamp(0.75rem, 2vw, 1rem)'
          }}
        >
          <Card percentage={37.5} label="45bar" />
        </div>

        {/* 左上角组件 */}
        <div
          className="absolute rounded-full flex items-center justify-center"
          style={{
            top: 'max(10%, 8px)',
            left: 'max(10%, 8px)',
            width: 'min(12%, 80px)',
            height: 'min(12%, 80px)',
            fontSize: 'clamp(0.625rem, 1.5vw, 0.875rem)'
          }}
        >
          <Card percentage={37.5} label="45bar" />
        </div>

        {/* 右上角组件 */}
        <div
          className="absolute rounded-full flex items-center justify-center"
          style={{
            top: 'max(10%, 8px)',
            right: 'max(10%, 8px)',
            width: 'min(10%, 48px)',
            height: 'min(10%, 48px)',
            fontSize: 'clamp(0.625rem, 1.5vw, 0.875rem)'
          }}
        >
          <Card percentage={37.5} label="45bar" />
        </div>

        {/* 左下角组件 */}
        <div
          className="absolute rounded-full flex items-center justify-center"
          style={{
            bottom: 'max(10%, 8px)',
            left: 'max(10%, 8px)',
            width: 'min(10%, 48px)',
            height: 'min(10%, 48px)',
            fontSize: 'clamp(0.625rem, 1.5vw, 0.875rem)'
          }}
        >
          <Card percentage={37.5} label="45bar" />
        </div>

        {/* 右下角组件 */}
        <div
          className="absolute rounded-full flex items-center justify-center"
          style={{
            bottom: 'max(10%, 8px)',
            right: 'max(10%, 8px)',
            width: 'min(10%, 48px)',
            height: 'min(10%, 48px)',
            fontSize: 'clamp(0.625rem, 1.5vw, 0.875rem)'
          }}
        >
          <Card percentage={37.5} label="45bar" />
        </div>
      </div>

    </div>
  );
};


export default CircularLayout;